#include <iostream>
#include <math.h>

#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <stdio.h>

#include "stb_image.h"

extern "C"
{
#include "shader.h"

}
#define SCR_WIDTH 800
#define SCR_HIGHT 600

// linux系统不需要判断多显卡
#ifndef linux
extern "C"
{
  // AMD
  __attribute__((dllexport)) int AmdPowerXpressRequestHighPerformance = 1;
  // Nvidia
  __attribute__((dllexport)) long NvOptimusEnablement = 0x00000001;
}
#endif

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);

void loadimg(unsigned int *texture, char const *path) {
    glGenTextures(1, texture);
    glBindTexture(GL_TEXTURE_2D, *texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);   
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // 加载并生成纹理
    stbi_set_flip_vertically_on_load(true);
    int width, height, nrChannels;
    unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0);
    if (data)
    {
        int format = GL_RGB;
        if (nrChannels == 3) {
            format = GL_RGB;
        } else if (nrChannels == 4) {
            format = GL_RGBA;
        }
        // printf("nrChannels: %d\n", nrChannels);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }    
    stbi_image_free(data);
}

void setUniforn1i(unsigned int program, char const *name, int value) {
    glUseProgram(program);
    glUniform1i(glGetUniformLocation(program, name), value);    
}

struct Vertex {
    float vx;
    float vy;
    float vz;
    float cx;
    float cy;
    float cz;
    float tx;
    float ty;
};

int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    #ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    #endif
    
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }
    // 注册视口回调函数
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    // 着色器
    unsigned int vs, fs, shaderProgram;
    compileShader(&vs, "res/texture.vs", GL_VERTEX_SHADER);
    compileShader(&fs, "res/texture.fs", GL_FRAGMENT_SHADER);
    linkProgram(&shaderProgram, &vs, &fs);

    
    
    // 顶点输入
    /*
    float vertices[] = {
        -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
         0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,  
         0.5f,  0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,  
        -0.5f,  0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f
    };
    */
    // 索引
    unsigned int indices[] = {
        0,  1,  2,
        0,  2,  3
    };
    Vertex vertices[] = {
        {-0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
        { 0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f},  
        { 0.5f,  0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f},  
        {-0.5f,  0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}
    };
    
    unsigned int VAO, VBO, EBO;
    // 创建顶点数组
    glGenVertexArrays(1, &VAO);
    // 创建顶点缓冲对象
    glGenBuffers(1, &VBO);
    // 创建顶点缓冲对象
    glGenBuffers(1, &EBO);
    // 绑定顶点数组
    glBindVertexArray(VAO);
    // 绑定顶点缓冲对象
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    // 顶点数据复制到当前绑定缓冲对象
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    // 绑定顶点缓冲对象
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    // 顶点数据复制到当前绑定缓冲对象
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
    // 设置顶点属性指针
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, cx));
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, tx));
    // 启用顶点属性 0
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    // 解除绑定顶点对象
    glBindBuffer(GL_ARRAY_BUFFER, 0); 
    // 解除绑定顶点数组
    glBindVertexArray(0); 
    
    
    // 纹理
    unsigned int texture1, texture2;
    loadimg(&texture1, "res/wall.jpg");
    loadimg(&texture2, "res/awesomeface.png");
    
    setUniforn1i(shaderProgram, "texture1", texture1);
    setUniforn1i(shaderProgram, "texture2", texture2);
    
    while(!glfwWindowShouldClose(window))
    {
        processInput(window);
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        glActiveTexture(GL_TEXTURE0 + texture1);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glActiveTexture(GL_TEXTURE1 + texture2);
        glBindTexture(GL_TEXTURE_2D, texture2);
        
        // 激活着色器程序
        glUseProgram(shaderProgram);
        
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        
        glfwSwapBuffers(window);
        glfwPollEvents();    
    }
    
    glfwTerminate();
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window)
{
    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}
